package cn.bisoft.java.service.ext.httpclient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.common.configuration.ConfigProvider;
import com.hengpeng.common.configuration.ConfigProviderFactory;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.SystemException;

public class HttpRequestProxy
{
	public final static String HTTP_REQUEST_CONTENTTYPE_APPLICATION_GZIP = "application/x-gzip";

	private static int connectTimeOut = 30000;

	private static final String HTTP_REQUEST_PROXY_CONNECT_TIME_OUT = "HttpRequestProxy.connectTimeOut";

	private static final String HTTP_REQUEST_PROXY_READ_TIME_OUT = "HttpRequestProxy.readTimeOut";

	private final static Log logger = LogFactory.getLog(HttpRequestProxy.class);

	private static int readTimeOut = 60000;

	static
	{
		try
		{
			ConfigProvider cp = ConfigProviderFactory.getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH);
			HttpRequestProxy.connectTimeOut = Integer.parseInt(cp.getConfigByPrimaryKey(
					HTTP_REQUEST_PROXY_CONNECT_TIME_OUT).toString());
			HttpRequestProxy.readTimeOut = Integer.parseInt(cp.getConfigByPrimaryKey(HTTP_REQUEST_PROXY_READ_TIME_OUT)
					.toString());
		}
		catch (Exception e)
		{
			logger.info("��ȡHttpReqeustProxy���������ļ�ʱ����, ����ֵ��ʹ��Ĭ��ֵ. ������Ϣ{" + e.getMessage() + "}");

		}
	}

	private static String connect(String requestURL, String requestContent, String requestMethod, int connectTimeout,
			int readTimeout, boolean useGZip)
	{
		HttpURLConnection url_con = null;
		String responseContent = null;
		URL url = null;
		BufferedWriter bw = null;
		BufferedReader br = null;
		OutputStream out = null;
		try
		{
			url = new URL(requestURL);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestProperty("User-Agent", "Mozilla/4.0");
			url_con.setConnectTimeout(connectTimeout);
			url_con.setReadTimeout(readTimeout);
			url_con.setRequestMethod(requestMethod);
			if ((requestContent != null) && (!requestContent.equalsIgnoreCase("")))
			{
				if (useGZip)
				{
					url_con.setRequestProperty("Content-Type", HTTP_REQUEST_CONTENTTYPE_APPLICATION_GZIP);
					url_con.setDoOutput(true);
					out = url_con.getOutputStream();
					GZIPOutputStream gzip = new GZIPOutputStream(out);
					bw = new BufferedWriter(new OutputStreamWriter(gzip));
					bw.write(requestContent);
				}
				else
				{
					url_con.setDoOutput(true);
					out = url_con.getOutputStream();
					bw = new BufferedWriter(new OutputStreamWriter(out));
					bw.write(requestContent);
				}

				bw.flush();
				bw.close();
				out.close();
			}

			url_con.connect();
			if (HTTP_REQUEST_CONTENTTYPE_APPLICATION_GZIP.equalsIgnoreCase(url_con.getContentType()))
			{
				br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url_con.getInputStream())));
			}
			else
			{
				br = new BufferedReader(new InputStreamReader(url_con.getInputStream()));
			}

			StringBuffer sb = new StringBuffer();
			char[] re = new char[1024];
			int len = 0;
			while ((len = br.read(re)) != -1)
			{
				sb.append(re, 0, len);
			}
			responseContent = sb.toString();
			br.close();
		}
		catch (IOException e)
		{
			logger.error("����URL{" + requestURL + "}ʱ�����������, �쳣��Ϣ{" + e.getMessage() + "}");
		}
		finally
		{
			if (url_con != null)
			{
				url_con.disconnect();
			}
			bw = null;
			out = null;
			br = null;
			url_con = null;
			url = null;
		}
		return responseContent;
	}

	public static String doGet(String reqUrl)
	{
		int paramIndex = reqUrl.indexOf("?");
		if (paramIndex != -1)
		{
			return HttpRequestProxy.doGet(reqUrl.substring(0, paramIndex), reqUrl.substring(paramIndex + 1, reqUrl
					.length()));
		}
		else
		{
			String requestContent = null;
			return HttpRequestProxy.doGet(reqUrl, requestContent);
		}
	}

	public static String doGet(String reqUrl, Map<String, String> parameters, String requestEncoding)
	{
		try
		{
			StringBuffer params = new StringBuffer();
			for (Iterator<Entry<String, String>> iter = parameters.entrySet().iterator(); iter.hasNext();)
			{
				Entry<String, String> element = iter.next();
				params.append(element.getKey());
				params.append("=");
				params.append(URLEncoder.encode(element.getValue().toString(), requestEncoding));
				params.append("&");
			}

			if (params.length() > 0)
			{
				params = params.deleteCharAt(params.length() - 1);
			}
			return HttpRequestProxy.doGet(reqUrl, params.toString());
		}
		catch (UnsupportedEncodingException e)
		{
			throw new SystemException(e);
		}
	}

	public static String doGet(String reqUrl, String parameter)
	{
		return HttpRequestProxy.connect(reqUrl, parameter, "GET", HttpRequestProxy.connectTimeOut,
				HttpRequestProxy.readTimeOut, false);
	}

	public static String doPost(String reqUrl, Map<String, String> parameters, String requestEncoding)
	{
		return HttpRequestProxy.doPost(reqUrl, parameters, requestEncoding, false);
	}

	public static String doPost(String reqUrl, Map<String, String> parameters, String requestEncoding, boolean useGZip)
	{
		try
		{
			StringBuffer params = new StringBuffer();
			if (useGZip)
			{
				for (Iterator<Entry<String, String>> iter = parameters.entrySet().iterator(); iter.hasNext();)
				{
					Entry<String, String> element = iter.next();
					params.append(element.getKey());
					params.append("=");
					params.append(element.getValue().toString());
					params.append("&");
				}
			}
			else
			{
				for (Iterator<Entry<String, String>> iter = parameters.entrySet().iterator(); iter.hasNext();)
				{
					Entry<String, String> element = iter.next();
					params.append(element.getKey());
					params.append("=");
					params.append(URLEncoder.encode(element.getValue().toString(), requestEncoding));
					params.append("&");
				}
			}

			if (params.length() > 0)
			{
				params = params.deleteCharAt(params.length() - 1);
			}
			return HttpRequestProxy.connect(reqUrl, params.toString(), "POST", HttpRequestProxy.connectTimeOut,
					HttpRequestProxy.readTimeOut, useGZip);

		}
		catch (UnsupportedEncodingException e)
		{
			throw new SystemException(e);
		}
	}

	public static String doPost(String reqUrl, String parameter)
	{
		return HttpRequestProxy.connect(reqUrl, parameter, "POST", HttpRequestProxy.connectTimeOut,
				HttpRequestProxy.readTimeOut, false);
	}
}
